package com.itbac.springsecurityoauth2demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * 客户端详情服务
 * 聪明的,自定义查询 Client的服务
 * 用于授权服务,是否可以进行授权
 * @author: BacHe
 * @email: 1218585258@qq.com
 * @Date: 2021/3/27 20:11
 */
@Component
public class SmartClientDetailsService implements ClientDetailsService  {

    //加密器
    @Autowired
    private PasswordEncoder passwordEncoder;

   //线上环境，需要使用 guava 缓存 + Redis缓存
    private Map<String, ClientDetails> clientDetailsStore = new HashMap();

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        ClientDetails details = (ClientDetails)this.clientDetailsStore.get(clientId);
        if (details == null) {
            //线上场景,需要查数据库。
            throw new NoSuchClientException("No client with requested id: " + clientId);
        } else {
            return details;
        }
    }

    public Map<String, ClientDetails> getClientDetailsStore() {
        return clientDetailsStore;
    }

    public SmartClientDetailsService setClientDetailsStore(Map<String, ClientDetails> clientDetailsStore) {
        this.clientDetailsStore = clientDetailsStore;
        return this;
    }

    public SmartClientDetailsService setClientDetailsStore(String key, ClientDetails clientDetails) {
        this.clientDetailsStore.put(key, clientDetails);
        return this;
    }

    @PostConstruct
    public void init(){
        //初始化一个 ClientDetails , 实际场景可以去查询数据库
        BaseClientDetails clientDetails = new BaseClientDetails();
        clientDetails.setClientId("admin");
        clientDetails.setClientSecret(passwordEncoder.encode("123456a"));
        clientDetails.setRegisteredRedirectUri(Collections.singleton("http://www.baidu.com"));
//        clientDetails.setRegisteredRedirectUri(Collections.singleton("http://localhost:8081/login"));
        clientDetails.setAccessTokenValiditySeconds(60*60*2);
        clientDetails.setRefreshTokenValiditySeconds(60*60*24);
        clientDetails.setScope(Collections.singletonList("all"));
        clientDetails.setAuthorizedGrantTypes(new ArrayList<>(Arrays.asList("authorization_code", "password", "refresh_token")));
        //自动授权
        clientDetails.setAutoApproveScopes(Collections.singletonList("all"));
        clientDetailsStore.put("admin", clientDetails);
    }
}
